<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="90" :formType="formType" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <FilterTable
      ref="table"
      columnsRef="finance_repairFinance_receivables_debtPayments"
      height="auto"
      :columns="columns"
      :datakey="'rows'"
      :isSelectColumn="false"
      :onSyncTableData="syncTableFun"
      :onColumnsChange="columns => (this.columns = columns)"
    ></FilterTable>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog(true)">取 消</el-button>
      <AjaxButton type="primary" :click="saveDialog" :disabled="confirmBtnDisabled">确 定</AjaxButton>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { setSettmentOrderDebt } from '@/api/finance/repair/receivables';
import { getUserId } from '@/assets/js/auth';
import { getAllUser } from '@/api/finance/advancesReceived/register';
import { notifyAction } from '@/utils';
export default {
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    return {
      formListPOS: [],
      index: null,
      formList: this.createFormList(),
      columns: this.createTableColumns(),
      formType: 'add',
      money: null,
      balance: null,
      balaPayobjId: null,
      // 定义存放结算单table
      lsita: []
    };
  },
  computed: {
    // 勾选欠款结算放开确定按钮
    confirmBtnDisabled() {
      return this.formList.find(item => item.fieldName == 'ARR_BALANCE').initialValue == 0;
    }
  },
  mounted() {
    this.getEmployee();
    this.formList.find(item => item.fieldName === 'receiveDate').initialValue = moment().format('YYYY-MM-DD HH:mm:ss');
    this.formList.find(item => item.fieldName === 'handler').initialValue = getUserId();
  },
  methods: {
    // 获取回调数据
    syncTableFun(val) {
      console.log(1);
      this.lsita = val;
      console.log('val:' + val);
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '收费对象代码',
          fieldName: 'paymentObjectCode',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '收费对象名称',
          fieldName: 'paymentObjectName',
          disabled: true
        },
        {
          type: 'SELECT',
          itemList: [],
          label: '经手人',
          fieldName: 'handler',
          disabled: true
        },
        {
          type: 'DATE',
          label: '收款日期',
          dateType: 'datetime',
          fieldName: 'receiveDate',
          disabled: true,
          hidden: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '收款金额',
          precision: 2,
          min: 0,
          fieldName: 'receiveAmount',
          disabled: true
        },
        {
          type: 'CHECKBOX',
          label: '是否欠款结算',
          fieldName: 'ARR_BALANCE',
          initialValue: 0,
          change: val => {
            console.log(val, '是否欠款变化');
            if (val == 1) {
              let totalAmount = this.formList.find(item => item.fieldName == 'receiveAmount').initialValue;
              if (totalAmount < 0) {
                notifyAction('收款金额为负不能欠款结算！', 'warning');
                this.closeDebtFeeSettlement();
                this.$nextTick(() => {
                  this.formList.find(item => item.fieldName == 'ARR_BALANCE').initialValue = 0;
                });
              } else {
                this.useDebtFeeSettlement();
              }
            } else {
              this.closeDebtFeeSettlement();
            }
          }
        },
        {
          type: 'INPUT',
          label: '担保方',
          fieldName: 'GUARANTOR',
          disabled: true,
          placeholder: '请输入...',
          rules: [{ required: false, message: '欠款结算担保方必填', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '欠款金额',
          fieldName: 'ARREARS_AMOUNT',
          disabled: true,
          initialValue: 0,
          isControls: false,
          precision: 2
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true
        },
        {
          title: '应收账款',
          dataIndex: 'RECEIVABLE_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已收账款',
          dataIndex: 'RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '已免账款',
          dataIndex: 'DERATED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '未收账款',
          dataIndex: 'NOT_RECEIVED_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '收款金额',
          dataIndex: 'RECEIVE_AMOUNT',
          precision: 2,
          sorter: true
        },
        {
          title: '是否结清',
          dataIndex: 'PAY_OFF',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.BALANCE_CLOSE, '1004')}</span>;
          }
        },
        {
          title: '已全部开票',
          dataIndex: 'IS_ALL_INVOICE',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.IS_ALL_INVOICE, '1004')}</span>;
          }
        },
        {
          title: '工单号',
          dataIndex: 'RO_NO',
          sorter: true,
          minWidth: 120
        },
        {
          title: '备件销售单号',
          dataIndex: 'SALES_PART_NO',
          sorter: true
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          sorter: true,
          minWidth: 180
        }
      ];
    },
    // 启用欠款结算
    useDebtFeeSettlement() {
      this.formList.find(item => item.fieldName == 'GUARANTOR').disabled = false;
      this.formList.find(item => item.fieldName == 'GUARANTOR').rules[0].required = true;
      // this.formList.find(item => item.fieldName == 'receiveAmount').disabled = true;
      this.formList.find(item => item.fieldName == 'ARREARS_AMOUNT').initialValue = this.formList.find(item => item.fieldName == 'receiveAmount').initialValue || 0;
    },
    // 关闭欠款结算
    closeDebtFeeSettlement() {
      this.formList.find(item => item.fieldName == 'GUARANTOR').disabled = true;
      this.formList.find(item => item.fieldName == 'GUARANTOR').initialValue = '';
      this.formList.find(item => item.fieldName == 'GUARANTOR').rules[0].required = false;
      // this.formList.find(item => item.fieldName == 'receiveAmount').disabled = false;
      this.formList.find(item => item.fieldName == 'ARREARS_AMOUNT').initialValue = 0;
    },
    openModel(data) {
      console.log('传入', data);
      this.balaPayobjId = data[0].BALA_PAYOBJ_ID;
      this.formList.find(item => item.fieldName === 'paymentObjectCode').initialValue = data[0].PAYMENT_OBJECT_CODE;
      this.formList.find(item => item.fieldName === 'paymentObjectName').initialValue = data[0].PAYMENT_OBJECT_NAME;
      let sum = 0;
      for (let i = 0; i < data.length; i++) {
        data[i].RECEIVE_AMOUNT = data[i].NOT_RECEIVED_AMOUNT;
        sum += data[i].RECEIVE_AMOUNT;
      }
      this.money = this.formList.find(item => item.fieldName === 'receiveAmount').initialValue = sum;
      this.$refs.table.EXECUTE_INSERT(data);
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async getEmployee() {
      const res = await getAllUser();
      // console.log(res, '经手人');
      this.formList.find(item => item.fieldName === 'handler').itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    // 点击确定
    async saveDialog() {
      try {
        let formData = await this.$refs.formPanel.GET_FORM_DATA();
        if (formData[0]) {
          let keys = Object.keys(formData[0]);
          return notifyAction(formData[0][keys[0]][0].message, 'warning');
        }
        let guarantor = formData[1].GUARANTOR;
        let balanceNoList = this.lsita.map(item => item.BALANCE_NO);
        try {
          let res = await setSettmentOrderDebt({
            balanceNos: balanceNoList.join(','),
            guarantor
          });
          if (res.resultCode == 200 && res.data) {
            notifyAction('欠款收款成功', 'warning');
            this.closeDialog(false);
          }
        } catch (err) {
          console.log(err);
        }
      } catch (err) {
        console.log(err);
      }
    },
    closeDialog(val) {
      this.$emit('close', val);
    }
  }
};
</script>
